import React, { memo, useLayoutEffect, useMemo, useState } from "react";
import domtoimage from "dom-to-image";
import { Button, Switch, message } from "antd";
import styles from "../index.module.scss";
import { totalContent } from "../_main";
import { Template } from "../_customization";
import { isClient, isProd } from "../../../utils";
import PersonalDetail from "./personalDetail/index";

import ContentItem from "./contentItem";
import ScrollWrapper from "@/app/components/ScrollWrapper";
import {
  useContentStore,
  useCustomizationStore,
  usePersonalDetailsStore,
  useStore,
} from "@/store";
import { blobToFile, getDisplayName } from "@/app/utils";
import { addTemplate, updateTemplates, uploadTemp } from "@/service";

function Index() {
  const { setCurrentTab, currentTab, setIndex, tempInfo } = useStore();
  const { title, description, templateName, order, classify } = tempInfo;
  const [mid, setMid] = useState(null);
  const [isCopy, setIscopy] = useState(false);
  const [uploadImage, setUploadImage] = useState(false);
  useLayoutEffect(() => {
    const query = new URLSearchParams(isClient() ? location.search : "");
    setMid(query.get("mid"));
    setIscopy(!!query.get("copy"));
  }, []);
  const { content } = useContentStore(
    (state) => state,
    (o, n) => {
      return currentTab !== "content";
    }
  );
  const { personalDetails } = usePersonalDetailsStore();

  const { customization } = useCustomizationStore(
    (state) => state,
    (o, n) => {
      return (
        currentTab !== "content" &&
        o.customization.layout.detailsPosition ===
          n.customization.layout.detailsPosition &&
        o.customization.layout.colsFromDetails ===
          n.customization.layout.colsFromDetails &&
        o.customization.sectionOrder === n.customization.sectionOrder
      );
    }
  );
  const { layout, sectionOrder } = customization;
  const { colsFromDetails, detailsPosition } = layout;

  const { leftSectionChildren, rightSectionChildren } =
    sectionOrder[colsFromDetails[detailsPosition || "top"]];
  function sortContent(content: ResumesContent) {
    const arr: Sections[] = [];
    let list = [];
    if (detailsPosition === "right") {
      list = leftSectionChildren.concat(rightSectionChildren || []);
    } else {
      list = (rightSectionChildren || []).concat(leftSectionChildren || []);
    }
    const keys = Object.keys(content);
    list.forEach((item) => {
      if (content[item]) {
        arr.push(item);
      }
    });
    return [...new Set([...arr, ...keys])];
  }

  const contentList = totalContent.filter((item) => !content[item]);
  const renderContent = useMemo(() => {
    return contentList.map((item) => {
      return (
        <div
          className={styles.toBeAddItem}
          onClick={() => {
            setCurrentTab(`${item}Edit`);
            setIndex(0);
          }}
          key={item}
        >
          {getDisplayName(item)}
          <button className={styles.plus}>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width={20}
              viewBox="0 0 19 19"
              fill="currentColor"
            >
              <path
                fillRule="evenodd"
                d="M10.8 2.452a1.3 1.3 0 10-2.6 0v5.316H2.885a1.3 1.3 0 000 2.6H8.2v5.315a1.3 1.3 0 002.6 0v-5.315h5.315a1.3 1.3 0 100-2.6H10.8V2.452z"
                clipRule="evenodd"
              ></path>
            </svg>
          </button>
        </div>
      );
    });
  }, [currentTab]);
  return (
    <ScrollWrapper>
      {(scrollWrapper) => (
        <>
          <Template />
          <PersonalDetail />
          {sortContent(content).map((item: Sections) => {
            return (
              <ContentItem
                scrollWrapper={scrollWrapper}
                key={item}
                type={item}
              ></ContentItem>
            );
          })}
          <div className={styles.toBeAdd}>{renderContent}</div>
          {!isProd ? (
            <div
              style={{
                width: "100%",
                gap: 10,
                display: "flex",
                justifyContent: "flex-end",
                alignItems: "center",
                background: "#fff",
                boxShadow: "rgba(0, 0, 0, 0.05) 2px 1px 7px",
                padding: "10px",
                borderRadius: "15px",
              }}
            >
              <Switch
                size="small"
                style={{ marginLeft: "20px" }}
                onChange={setUploadImage}
              />
              <Button
                onClick={async () => {
                  window.location.href = "/templateMake";
                }}
              >
                取消
              </Button>
              <Button
                type="primary"
                onClick={async () => {
                  const node = document
                    .querySelector(".paper0")
                    .cloneNode(true);
                  document.body.append(node);
                  (node as any).style.zoom = 1.5;
                  // (node as any).style.position = 'fixed';
                  // (node as any).style.left = '-10000px';
                  // (node as any).style.transformOrigin = 'left top'
                  const blob = await domtoimage.toBlob(node, {
                    width: 820 * 1.5, // 高度宽度自行设定
                    height: 1160 * 1.5,
                  });
                  document.body.removeChild(node);
                  const file = blobToFile(blob, "模板.jpeg", "image/png");

                  const formData = new FormData();

                  formData.append("file", file);
                  let templateUrl = "";
                  if (uploadImage) {
                    const res = await uploadTemp(formData);
                    if (res.code === 200) {
                      templateUrl = res.data;
                    }
                  }

                  const personalDetail = JSON.parse(
                    JSON.stringify(personalDetails)
                  );
                  const content2 = JSON.parse(JSON.stringify(content));
                  const customization2 = JSON.parse(
                    JSON.stringify(customization)
                  );
                  delete customization2.id;
                  delete customization2.resumeId;
                  Object.keys(content2).forEach((item, index) => {
                    delete content2[item].id;
                    delete content2[item].resumeId;
                    content2[item].key = index;
                    content2[item].entries = content2[item].entries.map(
                      (e, index) => {
                        const a = {
                          ...e,
                          key: index,
                        };
                        delete a.id;
                        delete a.contentId;
                        return a;
                      }
                    );
                  });
                  delete personalDetail.id;
                  const data = {
                    personalDetails: personalDetail,
                    content: content2,
                    customization: customization2,
                    templateName: templateName || "tpl1",
                    templateUrl,
                    title,
                    description,
                    order,
                    classify,
                  };
                  if (!templateUrl) {
                    delete data.templateUrl;
                  }
                  if (mid && !isCopy) {
                    const res = await updateTemplates({
                      id: mid,
                      ...data,
                    });
                    if (res.code === 200) {
                      message.success("修改成功");
                    }
                  } else {
                    const res = await addTemplate(data);
                    if (res.code === 200) {
                      message.success("新增成功");
                    }
                  }
                }}
              >
                {mid && !isCopy ? "修改" : "新增"}
              </Button>
            </div>
          ) : null}
        </>
      )}
    </ScrollWrapper>
  );
}

export default memo(Index, () => {
  return true;
});
